<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/6/25
 * Time: 16:45
 */

namespace app\admin\controller;

use app\common\model\Notice as NoticeModel;
use app\common\model\Article as ArticleModel;
use app\common\model\ArticleSon as ArticleSonModel;
use app\common\model\Area as AreaModel;
use app\common\model\User as UserModel;
use think\Db;
use think\Request;

class Message extends \app\admin\controller\Base
{
    protected $res = array(
        'systemindex' => array('css' => '2,3,4', 'js' => 'list,My97DatePicker'),
        'systemadd' => array('css' => '2,3,4,5,9,select-css', 'js' => 'ueditor_config,ueditor_all,ueditor_lang,select-js'),
        'systemdetails' => array('css' => '2,3,4,5,9', 'js' => 'ueditor_config,ueditor_all,ueditor_lang'),
        'systemupdate' => array('css' => '2,3,4,5,9,select-css', 'js' => 'ueditor_config,ueditor_all,ueditor_lang,select-js'),
        'accurateindex' => array('css' => '2,3,4', 'js' => 'list,My97DatePicker'),
        'accuratedetails' => array('css' => '2,3,4,5,9', 'js' => 'ueditor_config,ueditor_all,ueditor_lang'),
        'commonindex' => array('css' => '2,3,4', 'js' => 'list,My97DatePicker'),
        'commondetails' => array('css' => '2,3,4,5,9', 'js' => 'ueditor_config,ueditor_all,ueditor_lang'),
        'articleadd' => array('css' => '2,3,4,5,9,select-css,uploadcss,uploadcss1', 'js' => 'My97DatePicker,select-js,uploadjs,uploadjs1'),
    
    );
    //权限
    protected $auth = [
        2 => '铜牌',
        3 => '银牌',
        4 => '金牌',
    ];
    //判断已读、未读、清空消息的字符串
    protected $str = ',0,';
    //消息种类
    protected $n_type = [
        1 => '优惠活动消息',
        2 => '举报下架通知',
        3 => '购买权限成功通知',
        4 => '反馈消息',
        5 => '审核中',
        6 => '审核成功',
        7 => '审核失败',
        8 => '权限即将过期',
        9 => '权限过期',
    ];
    /**
     * 系统消息列表展示
     * @return mixed
     */
    public function systemIndex()
    {
        $search = input('param.search/a');
        $page = input('param.page');
        $search = $this->search($search, $page);
        if(!$page) {
            $pages = 0;//进入后台没有pages时，page置0
        } else {
            $pages = ($page - 1) * 15;//用于生成序号
        }
        $where = $this->getSystemWhere($search);
        $noticeModel = new NoticeModel();
        $list = $noticeModel->getNoticeLists($where, 15);
        foreach($list as &$val) {//将时间改为年月日时分形式展示
            $val['n_createtime'] = date('Y-m-d H:i', strtotime($val['n_createtime']));
        }
        $this->assign(array(
            'search' => $search,
            'page' => $page,
            'list' => $list,
            'pages' => $pages,
            'n_type' => $this->n_type
        ));
        return $this->fetch();
    }
    
    /**
     * 精准消息列表
     * @return mixed
     */
    public function accurateIndex()
    {
        $search = input('param.search/a');
        $page = input('param.page');
        $search = $this->search($search, $page);
        if(!$page) {
            $pages = 0;
        } else {
            $pages = ($page - 1) * 15;//用于生成序号
        }
        //查询字段
        $field = 'a.a_id, a.a_title, a.a_createtime, a.a_num, a.a_auth_type, a.a_type, a.a_down,
                 ua1.district as city, ua2.district as province, ua3.district, 
                 uuu.user_image, uuu.user_username, uuu.user_phone';
        $whereA = $this->getAccurateWhere($search);//获取查询条件
        $articleModel = new ArticleModel();
        $lists = $articleModel->getArticleInfo($field, $whereA, 15);//列表
        $wherePro['level'] = 1;
        if($search[5] != '') {
            $whereCity['pid'] = $search[5];
        } else {
            $whereCity['pid'] = 2;
        }
        $areaModel = new AreaModel();
        //省
        $province = $areaModel->selectArea($wherePro);
        //市
        $city = $areaModel->selectArea($whereCity);
        $this->assign([
            'lists' => $lists,
            'pages' => $pages,
            'page' => $page,
            'a_type' => ArticleModel::$a_type,
            'a_auth_type' => ArticleModel::$a_auth_type,
            'search' => $search,
            'province' => $province,//省
            'city' => $city,//市
            'auth' => $this->auth
        ]);
        return $this->fetch();
    }
    
    /**
     * 普通消息列表
     * @return mixed
     */
    public function commonIndex()
    {
        $search = input('param.search/a');
        $page = input('param.page');
        $search = $this->search($search, $page);
        if(!$page) {
            $pages = 0;
        } else {
            $pages = ($page - 1) * 15;//用于生成序号
        }
        //查询字段
        $field = 'a.a_id, a.a_title, a.a_createtime, a.a_num, a.a_auth_type, a.a_type, a.a_down,
                 ua1.district as city, ua2.district as province, ua3.district, 
                 uuu.user_image, uuu.user_username, uuu.user_phone';
        $whereA = $this->getCommonWhere($search);//获取查询条件
        $articleModel = new ArticleModel();
        $lists = $articleModel->getArticleInfo($field, $whereA, 15);//列表
        $wherePro['level'] = 1;
        if($search[5] != '') {
            $whereCity['pid'] = $search[5];
        } else {
            $whereCity['pid'] = 2;
        }
        $areaModel = new AreaModel();
        //省
        $province = $areaModel->selectArea($wherePro);
        //市
        $city = $areaModel->selectArea($whereCity);
        $this->assign([
            'lists' => $lists,
            'pages' => $pages,
            'page' => $page,
            'a_type' => ArticleModel::$a_type,
            'search' => $search,
            'province' => $province,//省
            'city' => $city,//市
        ]);
        return $this->fetch();
    }
    
    /**
     * 后台发布信息
     * @return mixed
     */
    public function articleAdd()
    {
        if(Request::instance()->isPost()) {
            $params = input('param.');
            if($params['a_title'] == ''){
                return $this->api_error('标题不能为空', '14001');
            }
            if($params['a_content'] == ''){
                return $this->api_error('内容不能为空', '14001');
            }
            if($params['photo'] == ''){
                return $this->api_error('图片不能为空', '14001');
            }
            if($params['a_phone'] == '' || !preg_match("/^1[345678]{1}\d{9}$/",$params['a_phone'])){
                return $this->api_error('请填写正确的手机', '14001');
            }
            if($params['a_createtime'] == ''){
                $params['a_createtime'] = date('Y-m-d H:i:s', time());
            }
            if($params['a_sheng'] == ''){
                return $this->api_error('请选择定位省份', '14001');
            }
            if($params['a_shi'] == ''){
                return $this->api_error('请选择定位城市', '14001');
            }
            if($params['publish_sheng'] == ''){
                return $this->api_error('请选择发布省份', '14001');
            }
            if($params['publish_shi'] == ''){
                return $this->api_error('请选择发布城市', '14001');
            }
            //图片
            $params['a_image'] = $params['photo'];
            unset($params['photo']);
            //根据发布权限，给a_auth_city赋值
            if($params['a_auth_type'] == 1 || $params['a_auth_type'] == 4){//普通和金牌置0
                $params['a_auth_city'] = 0;
            }
            if($params['a_auth_type'] == 2){//铜牌 赋发布城市
                $params['a_auth_city'] = $params['publish_shi'];
            }
            if($params['a_auth_type'] == 3){//银牌 赋发布省份
                $params['a_auth_city'] = $params['publish_sheng'];
            }
            $params['a_year'] = substr($params['a_createtime'], 0, 4);
            $articleModel = new ArticleModel();
            $res = $articleModel->creatArticle($params);
            if($res) {
                $as_article_id = $articleModel->a_id;//获取新增记录id
                $data = [
                    'as_article_id' => $as_article_id,
                    'as_time' => $params['a_createtime'],
                    'as_read_users' => $this->str,
                    'as_clear_users' => $this->str,
                ];
                $time = date('Y-m-d');
                /*---- 推送标题 start ----*/
                if(mb_strlen($params['a_title'], 'utf8') > 10){
                    $title = mb_substr($params['a_title'], 0, 10, 'utf-8') . '......';
                }else{
                    $title = $params['a_title'];
                }
                /*---- 推送标题 end ----*/
                $lists = [];
                $userModel = new UserModel();
                //如果是铜牌发布，则需在a_article_son中插入一条数据，并进行推送
                if($params['a_auth_type'] == 2) {
                    $num = $this->publishFollow($data, $time);
                    if($num < 10) {
                        $list = $userModel->getPushUser('user_shi', $params['a_auth_city']);
                        if($list){
                            foreach($list as $val){
                                $va = (string)$val;
                                array_push($lists, $va);
                            }
                            //推送 参数1.被推送的用户 数组  2.标识  3.推送的方式  4.推送内容 数组
                            $this->Jpush($lists, $title, 1, ['type'=>1]);
                            //推送记录表，推送次数自增1
                            Db::name('pushnum')->where('pushtime', $time)->setInc('pushnum');
                        }
                    }
                }
                //如果是银牌发布，则需在a_article_son中插入一条数据，并进行推送
                if($params['a_auth_type'] == 3) {
                    $num = $this->publishFollow($data, $time);
                    if($num < 10) {
                        $list = $userModel->getPushUser('user_sheng', $params['a_auth_city']);
                        if($list){
                            foreach($list as $val){
                                $va = (string)$val;
                                array_push($lists, $va);
                            }
                            $this->Jpush($lists, $title, 1, ['type'=>1]);
                            Db::name('pushnum')->where('pushtime', $time)->setInc('pushnum');
                        }
                    }
                }
                //如果是金牌发布，则需在a_article_son中插入一条数据，并进行推送
                if($params['a_auth_type'] == 4) {
                    $num = $this->publishFollow($data, $time);
                    if($num < 10) {
                        $this->Jpush('', $title, 2, ['type'=>1]);
                        Db::name('pushnum')->where('pushtime', $time)->setInc('pushnum');
                    }
                }
                return $this->api_success('发布成功',200);
            } else {
                return $this->api_error('发布失败', '14001');
            }
        } else {
            //获取虚拟用户信息
            $dummyUser = Db::name('u_user')->field('user_id, user_username')->where('user_type', 2)->select();
            $where['level'] = 1;
            $whereCity['pid'] = 2;
            $areaModel = new AreaModel();
            $province = $areaModel->selectArea($where);
            $city = $areaModel->selectArea($whereCity);
            $this->assign([
                'dummyUser' => $dummyUser,
                'a_type' => ArticleModel::$a_type,
                'a_auth_type' => ArticleModel::$a_auth_type,
                'province' => $province,
                'city'  =>  $city
            ]);
            return $this->fetch();
        }
    }
    
    /**
     * 添加系统消息
     * @return mixed|\think\response\Json
     */
    public function systemAdd()
    {
        if(Request::instance()->isPost()) {
            $data['n_title'] = input('param.n_title');
            $data['n_content'] = input('param.n_content');
            if($data['n_title'] == ''){
                return $this->api_error('标题不能为空', '14001');
            }
            if($data['n_content'] == ''){
                return $this->api_error('内容不能为空', '14001');
            }
            $n_send_type = input('param.n_send_type/a');
            $data['n_send_type'] = $n_send_type[0];
            if($data['n_send_type'] == 2) {
                $data['n_user_id'] = input('param.n_user_id');
            }
            $data['n_createtime'] = date('Y-m-d H:i:s');
            $data['n_type'] = input('param.n_type');
            $data['n_read_users'] = $this->str;
            $data['n_clear_users'] = $this->str;
            $noticeModel = new NoticeModel();
            $res = $noticeModel->createSystemMessage($data);
            $content = $this->n_type[$data['n_type']];
            if($res) {
                if($data['n_type'] != 1){//非优惠活动消息，自动推送
                    if($data['n_send_type'] == 1){//推所有人
                        $this->Jpush('', $content, 2, array('type'=>'sys'));
                    }else{//推个人
                        $user_id = (string)$data['n_user_id'];
                        $this->Jpush($user_id, $content, 1, array('type'=>'sys'));
                    }
                }
                return $this->api_success('操作成功');
            } else {
                return $this->api_error('操作失败');
            }
        } else {
            $page = input('param.page');
            $list = Db::name('u_user')->field('user_username, user_id')->where('user_type', 1)->select();
            $n_type = Db::name('notice_type')->select();
            $this->assign(array(
                'page' => $page,
                'list' => $list,
                'n_type' => $n_type
            ));
            return $this->fetch();
        }
    }
    
    /**
     * 手动推送系统消息
     * @return string
     *
     */
    public function systemPublish(){
        $n_id = input('param.n_id');
        $n_title = input('param.n_title');
        $noticeModel = new NoticeModel();
        $res = $noticeModel->getOneInfo($n_id);
        if($res['n_send_type'] == 1){//推送给所有用户
            $result = $this->Jpush('', '优惠活动通知', 2, '');
        }else{//推送给个人
            $id =  (string)$res['n_user_id'];
            $result = $this->Jpush($id, '优惠活动通知', 1, '');
        }
        $data = ['code' => $result['http_code']];
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
    
    /**
     * 删除系统消息
     * @return \think\response\Json
     */
    public function systemDel()
    {
        $ids = strtoarray(input('post.ids'));
        $noticeModel = new NoticeModel();
        $where['n_id'] = array('In', $ids);
        $result = $noticeModel->where($where)->delete();
        if($result) {
            return $this->api_success('操作成功');
        } else {
            return $this->api_dbError();
        }
    }
    
    /**
     * 查看详细的系统消息
     * @return mixed
     */
    public function systemDetails()
    {
        $n_id = input('param.n_id');
        $page = input('param.page');
        $noticeModel = new NoticeModel();
        $list = $noticeModel->getOneInfo($n_id);
        $this->assign(array(
            'list' => $list,
            'page' => $page,
            'n_type' => $this->n_type
        ));
        return $this->fetch();
    }
    
    /**
     * 修改系统消息
     * @return mixed|\think\response\Json
     */
    public function systemUpdate()
    {
        if(Request::instance()->isPost()) {
            $n_id = input('param.n_id');
            $data['n_title'] = input('param.n_title');
            $data['n_content'] = input('param.n_content');
            $n_send_type = input('param.n_send_type/a');
            $n_user_id = input('param.n_user_id/a');
            $data['n_send_type'] = $n_send_type[0];
            if($data['n_send_type'] == 2) {
                $data['n_user_id'] = $n_user_id[0];
            }
            //如果从单个用户修改成所有用户，那么表中n_user_id字段置null
            if($data['n_send_type'] == 1) {
                $data['n_user_id'] = null;
            }
            $data['n_createtime'] = date('Y-m-d H:i:s');
            $data['n_type'] = input('param.n_type');
            $noticeModel = new NoticeModel();
            $res = $noticeModel->updateSystemMessage($n_id, $data);
            $content = $this->n_type[$data['n_type']];
            if($res) {
                if($data['n_type'] != 1){//非优惠活动消息，自动推送
                    if($data['n_send_type'] == 1){//推所有人
                        $this->Jpush('', $content, 2, array('type'=>'sys'));
                    }else{//推个人
                        $user_id = (string)$data['n_user_id'];
                        $this->Jpush($user_id, $content, 1, array('type'=>'sys'));
                    }
                }
                return $this->api_success('操作成功');
            } else {
                return $this->api_error('操作失败');
            }
        } else {
            $n_id = input('param.n_id');
            $page = input('param.page');
            $noticeModel = new NoticeModel();
            $list = $noticeModel->getOneInfo($n_id);
            $users = Db::name('u_user')->field('user_username, user_id')->where('user_type', 1)->select();
            $n_type = Db::name('notice_type')->select();
            $this->assign(array(
                'list' => $list,
                'users' => $users,
                'page' => $page,
                'n_type' => $n_type
            ));
            return $this->fetch();
        }
    }
    
    /**
     * 删除消息 软删除 a_del字段设置为2
     * @return \think\response\Json
     */
    public function articleDel()
    {
        $ids = strtoarray(input('post.ids'));
        $articleModel = new ArticleModel();
        $where['a_id'] = array('In', $ids);
        $result = $articleModel->where($where)->setField('a_del', 2);
        if($result) {
            return $this->api_success('操作成功');
        } else {
            return $this->api_dbError();
        }
    }
    
    /**
     * 查看详细的精准消息
     * @return mixed
     */
    public function accurateDetails()
    {
        $a_id = input('param.a_id');
        $page = input('param.page');
        //查询字段
        $field = 'a.a_id, a.a_title, a.a_content, a.a_createtime, a.a_num, a.a_auth_type, a.a_type, a.a_phone, a.a_image, 
                 ua1.district as city, ua2.district as province, ua3.district, 
                 uuu.user_image, uuu.user_username, uuu.user_phone, ur.report_id';
        $articleModel = new ArticleModel();
        $list = $articleModel->getArticleInfo($field, '', '', $a_id);//列表
        $list['a_image'] = explode(',', trim($list['a_image'], ','));
        $this->assign([
            'list' => $list,
            'page' => $page,
            'a_type' => ArticleModel::$a_type,
            'a_auth_type' => ArticleModel::$a_auth_type
        ]);
        return $this->fetch();
    }
    
    /**
     * 查看详细的普通消息
     * @return mixed
     */
    public function commonDetails()
    {
        $a_id = input('param.a_id');
        $page = input('param.page');
        //查询字段
        $field = 'a.a_id, a.a_title, a.a_content, a.a_createtime, a.a_num, a.a_auth_type, a.a_type, a.a_phone, a.a_image, 
                 ua1.district as city, ua2.district as province, ua3.district, 
                 uuu.user_image, uuu.user_username, uuu.user_phone, ur.report_id';
        $articleModel = new ArticleModel();
        $list = $articleModel->getArticleInfo($field, '', '', $a_id);//列表
        $list['a_image'] = explode(',', trim($list['a_image'], ','));
        $this->assign([
            'list' => $list,
            'page' => $page,
            'a_type' => ArticleModel::$a_type
        ]);
        return $this->fetch();
    }
    
    /**
     * 被举报下架
     * @return string
     */
    public function articleDown(){
        $a_id = input('param.a_id');
        $res = Db::name('article')->where('a_id', $a_id)->setField('a_down', 2);
        if($res){
            $result = Db::name('article')->field('a_user_id, a_title')->where('a_id', $a_id)->find();
            $user_id = (string)$result['a_user_id'];
            $this->Jpush($user_id, '举报下架通知', 1, '');
            $data = ['code' => 200, 'msg' => '操作成功'];
        }else{
            $data = ['code' => 300, 'msg' => '操作失败'];
        }
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
    
    /**
     * 获取系统消息的查询条件数组
     * @param $search  查询条件
     * @return array
     */
    public function getSystemWhere($search)
    {
        $whereS = [];
        if($search[0] != '') {
            $whereS['n_title'] = ['like', '%' . $search[0] . '%'];
        }
        if($search[1] != '' && $search[2] != '') {
            $whereS['n_createtime'] = array('between', array($search[1], $search[2]));
        } elseif($search[1] != '') {
            $whereS['n_createtime'] = ['>', $search[1]];
            
        } elseif($search[2] != '') {
            $whereS['n_createtime'] = ['<', $search[2]];
        }
        return $whereS;
    }
    
    /**
     * 获取精准发布查询条件数组
     * @param $search  查询条件
     * @return array
     */
    public function getAccurateWhere($search)
    {
        $whereA = $this->getWhere($search);
        if($search[7] != '') {//发布权限
            $whereA['a.a_auth_type'] = ['=', $search[7]];
        }
        $whereA['a_auth_type'] = ['neq', 1];//精准发布
        $whereA['a_del'] = ['=', 1];//未被删除的
        return $whereA;
    }
    
    /**
     * 获取普通发布查询条件数组
     * @param $search  查询条件
     * @return array
     */
    public function getCommonWhere($search)
    {
        $whereA = $this->getWhere($search);
        $whereA['a_auth_type'] = ['eq', 1];//普通发布
        $whereA['a_del'] = ['=', 1];//未被删除的
        return $whereA;
    }
    
    /**
     * 获取发布信息查询条件数组
     * @param $search  查询条件
     * @return array
     */
    public function getWhere($search)
    {
        $whereA = [];
        if($search[0] != '') {//关键字
            $whereA['a.a_id|a.a_title|uuu.user_phone'] = ['like', '%' . $search[0] . '%'];
        }
        if($search[1] != '' && $search[2] != '') {//日期
            $whereA['a.a_createtime'] = ['between', [$search[1], $search[2]]];
        } elseif($search[1] != '') {
            $whereA['a.a_createtime'] = ['>', $search[1]];
        } elseif($search[2] != '') {
            $whereA['a.a_createtime'] = ['<', $search[2]];
        }
        if($search[3] != 0 && $search[4] != '') {//浏览量
            $whereA['a.a_num'] = ['between', [$search[3], $search[4]]];
        } elseif($search[3] != 0) {
            $whereA['a.a_num'] = ['>=', $search[3]];
        } elseif($search[4] != '') {
            $whereA['a.a_num'] = ['<=', $search[4]];
        }
        if($search[5] != '') {//省
            $whereA['a.a_sheng'] = ['=', $search[5]];
        }
        if($search[6] != '') {//市
            $whereA['a.a_shi'] = ['=', $search[6]];
        }
        return $whereA;
    }
    
    /**
     * 查询市
     */
    public function city()
    {
        $city = $_POST['city'];
        $cityArray = Db::table('up_area')->where('pid', $city)->select();
        $data['cityArray'] = $cityArray;
        return json($data);
    }
    
    /**
     * 图片上传
     */
    public function upload()
    {
        $tmp = $_FILES['file']['tmp_name'];
        $name = $_FILES['file']['name'];
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url = "http://" . $_SERVER['HTTP_HOST'];
        if($tmp) {
            //=======重命名=====
            $rand = date('YmdHis') . rand(100000, 999999);
            $exe = explode('.', $name);
            $exe = end($exe);
            $newName = $rand . '.' . $exe;
            $path = "{$dir}/image/";
                if(!file_exists($path)){
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($path, 0700,true);
                }
            //=======================
            if(move_uploaded_file($tmp, $path.$newName)) {
                echo "{$url}/image/{$newName}";
            } else {
                $file = $file = request()->file('file');
                echo $file->getError();
            }
        }
    }
    
    /**
     * 图片删除
     * @return \think\response\Json
     */
    public function deleteImg(){
        $add  = input('add');
        $url =  "http://".$_SERVER['HTTP_HOST'].'/';
        $add = str_replace ($url,'',$add);
        if(unlink($add)){
            return json(['code'=>200,'msg'=>'删除成功！']);
        }else{
            return json(['code'=>100,'msg'=>'删除失败！']);
        }
    }
    
    /**
     * 获取当天推送的消息条数
     * @return mixed
     */
    private function getPushNum($time)
    {
        $nums = Db::name('pushnum')->where('pushtime', $time)->value('pushnum');
        return $nums;
    }
    
    /**
     * 发布成功后的后续操作  1.插入a_article_son表
     *                     2.查询up_pushnum表中是否有当天推送的记录，如果没有创建记录
     * @param $data
     * @param $time
     */
    private function publishFollow($data, $time)
    {
        $articleSonModel = new ArticleSonModel();
        $articleSonModel->createRow($data);
        $num = $this->getPushNum($time);
        //如果没有记录，则先创建一条记录
        if($num === null) {
            Db::name('pushnum')->insert(['pushtime' => $time]);
        }
        return $num;
    }
}